<template>
  <div class="head">
    <!-- 欢迎光临小c的游戏屋~请&nbsp;&nbsp;&nbsp;&nbsp;<router-link to="/login">登录</router-link>&nbsp;&nbsp;&nbsp;&nbsp;<router-link class="test" to="/register">免费注册</router-link> -->
    <div class="head_left">欢迎光临小c的游戏屋</div>
    <div class="head_right" v-if="!isAuthorized">
      <router-link to="/login">登录</router-link
      >&nbsp;&nbsp;&nbsp;&nbsp;<router-link class="test" to="/register"
        >免费注册</router-link
      >
    </div>
    <div class="head_right" v-else>
      欢迎您：<span class="username">{{ user.user.username }}</span
      >&nbsp;&nbsp;&nbsp;&nbsp;
      <el-link type="info" @click="exitLogin" :underline="false">退出登录</el-link>
    </div>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
import { getUserInfo } from "@/api/index";
export default {
  created() {
    if (this.isAuthorized) {
      // Session是具有有效期的，设置更新令牌的触发器
      this.refreshSessionTrigger();
      // Session中有用户，而账号中没有，说明是通过“保存当前登陆状态”得到的，从服务端获取一下用户信息
      if (!this.user.username) {
        this.refreshUser();
      }
    }
  },
  computed: {
    ...mapGetters(["isAuthorized"]),
    ...mapState(["user", "session"]),
  },
  methods: {
    ...mapMutations(["updateUser", "clearSession"]),
    ...mapActions(["refreshSessionTrigger"]),
    /**
     * 从服务端请求用户信息，更新到vuex中
     */
    async refreshUser() {
      let res = await getUserInfo();
      this.updateUser(res.data);
    },

    /**
     * 退出登陆
     */
    exitLogin() {
      this.clearSession();
    },
  },
};
</script>

<style lang="less" scoped>
.head {
  width: 100%;
  height: 40%;
  line-height: 32px;
  background-color: #131313;
  float: left;
}
.head_left {
  float: left;
  height: 100%;
  overflow: hidden;
  color: #a5aab8;
  font-size: 12px;
  margin-left: 10%;
}
.head_right {
  height: 100%;
  overflow: hidden;
  color: #a5aab8;
  font-size: 12px;
  margin-left: 85%;
}
a {
  color: #a5aab8;
  text-decoration: none;
}
.username {
  color: greenyellow;
}
</style>